package com.xpu.shardingjdbc.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class DbPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        //获取片键名称
        String columnName = preciseShardingValue.getColumnName();
        System.out.println(columnName);
        //获取表名称->获取的是逻辑表名称
        String logicTableName = preciseShardingValue.getLogicTableName();
        System.out.println(logicTableName);
        //获取此时拆线呢的片键值
        Long value = preciseShardingValue.getValue();
        //根据获取的片键后，经过自定义的运算，获取对应的数据源名称
        //获取对应的数据源索引为
        long idx = (value % 2) + 1;
        //从数据源集合在查询指定idx结尾的数据源名称过滤出来
        String dsName = collection.stream().filter(name -> name.endsWith(idx + "")).findFirst().get();
        return dsName;
    }
}
